package com.gitee.cashzhang27.test.boot.graphql.webmvc.resolvers;

import com.gitee.cashzhang27.test.boot.graphql.webmvc.component.CharacterRepository;
import com.gitee.cashzhang27.test.boot.graphql.webmvc.types.Character;
import com.gitee.cashzhang27.test.boot.graphql.webmvc.types.Droid;
import com.gitee.cashzhang27.test.boot.graphql.webmvc.types.Episode;
import com.gitee.cashzhang27.test.boot.graphql.webmvc.types.Human;
import graphql.kickstart.tools.GraphQLQueryResolver;
import graphql.schema.DataFetchingEnvironment;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class Query implements GraphQLQueryResolver {

  private CharacterRepository characterRepository;

  public Character hero(Episode episode) {
    return episode != null
        ? this.characterRepository.getHeroes().get(episode)
        : this.characterRepository.getCharacters().get("1000");
  }

  public Human human(String id, DataFetchingEnvironment env) {
    return (Human)
        this.characterRepository.getCharacters().values().stream()
            .filter(character -> character instanceof Human && character.getId().equals(id))
            .findFirst()
            .orElseGet(null);
  }

  public Droid droid(String id) {
    return (Droid)
        this.characterRepository.getCharacters().values().stream()
            .filter(character -> character instanceof Droid && character.getId().equals(id))
            .findFirst()
            .orElseGet(null);
  }

  public Character character(String id) {
    return this.characterRepository.getCharacters().get(id);
  }
}
